<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use Auth;
use Hash;
class UserController extends Controller
{
	public function __construct () {
		//$this->middleware('auth')->except (['store']);
		$this->middleware('checklogin');
	}

	/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
    	$users=User::paginate(12);
        return view('user.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('user.register');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserRequest $request)
    {

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
    	$user=User::find($id);
    	$blogs=$user->blog()->paginate (3);
        return view('user.show',compact('user','blogs'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user)
    {
    	$this->authorize ('update',$user);
			return view('user.edit',compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, User $user)
    {
        $this->validate ($request,[
        	'name'=>'required',
			'oldpassword'=>'nullable|min:5',
			'password'=>'nullable|confirmed|min:5'
		]);
        $data=[
        	'name'=>$request->name
		];
        if($request->oldpassword){
        	if(!Hash::check ($request->oldpassword,$user->password)){
				session()->flash('danger','旧密码不正确！');
				return redirect ()->back ();
			}
			$data['password']=bcrypt($request->password);
		}elseif($request->password){
			session()->flash('danger','请填写旧密码');
			return redirect ()->back ();
		}
        $user->update ($data);
        session()->flash ('success','修改成功');
        return redirect ()->route('home');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        $this->authorize ('delete',$user);
        User::destroy ($user->id);
        session()->flash('success','删除成功！');
        return redirect ()->back();
    }
}
